//
//  OAuthiewController.swift
//  WeiBo
//
//  Created by Tony on 2018/1/7.
//  Copyright © 2018年 Tony. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthiewController: UIViewController {

    @IBOutlet weak var webView: UIWebView!
    var isFull: Bool = false
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // UI
        setup()
        
        // 加载webView
        loadPage()
    }
}

extension OAuthiewController {
    
    /// UI
    func setup() {
        title = "登录"
        navigationItem.leftBarButtonItem = UIBarButtonItem.init(title: "关闭", style: .plain, target: self, action: #selector(OAuthiewController.clickCloseBtn))
        navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "填充", style: .plain, target: self, action: #selector(OAuthiewController.clickFillBtn))
    }

    /// 加载网页
    func loadPage() {
        
        // 1.获取登录页面的URLString
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(app_key)&redirect_uri=\(redirect_uri)"
        
        // 2、创建url
        guard let url = NSURL.init(string: urlString) else {
            return
        }
        
        // 3、创建reqest
        let request = URLRequest.init(url: url as URL)
        
        /*
         NSURL的构造方法
         public init?(string URLString: String)
         
         URLRequest
         public init(url: URL)
         
         那么调用URLRequest的构造方法时，不需要guard语法来调用
         */
        
        // 4、加载
        webView.loadRequest(request)
        
        // 5、设置代理
        webView.delegate = self

    }
}

// MARK: -事件监听
extension OAuthiewController {
    func clickCloseBtn() {
        dismiss(animated: true, completion: nil)
    }
    
    func clickFillBtn() {
        // jave与javescrpt的区别，是雷锋与雷锋塔的区别
        // 执行javescrpt
        let userIdCode = "document.getElementById('userId').value='237612118@qq.com';"
        let passwdCode = "document.getElementById('passwd').value='qwert123456';"
        let jsCode = userIdCode + passwdCode
        
        webView.stringByEvaluatingJavaScript(from: jsCode)
        
    }
}

// MARK：-webView代理
extension OAuthiewController: UIWebViewDelegate {
    
    /// 开始加载
    func webViewDidStartLoad(_ webView: UIWebView) {
        
        SVProgressHUD.show()
    }
    
    /// 加载完成
    func webViewDidFinishLoad(_ webView: UIWebView) {
        
        if isFull == true {
            clickFillBtn()
        }
        isFull = false
        
        SVProgressHUD.dismiss()
    }
    
    /// 加载完成
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        
        SVProgressHUD.dismiss()
    }
    
    /// 拦截请求
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlStr = request.url?.absoluteURL.absoluteString
        
        if (urlStr?.contains("https://api.weibo.com/oauth2/authorize?client_id"))! {
            isFull = true
        }
        guard (urlStr?.contains("code="))! else {
            // 只没有加载到code。需要继续加载网页
            return true
        }
        
        // "https://m.baidu.com/?code=a0048906e75f2ba30254929f9f342f4d&from=844b&vit=fps"
        let tempArr = urlStr?.components(separatedBy: "code=")
        let codeArr = tempArr?[1].components(separatedBy: "&")
        let code = codeArr?[0]
        
        // 请求accessToken
        loadAccessToken(code: code!)
        
        return false
    }
    
}

// MARK: -请求accessToken
extension OAuthiewController {
    func loadAccessToken(code: String) {
        HttpTool.shareInstance.loadAccessToken(code: code) { [weak self](result: AnyObject?, error: Error?) -> (Void) in
            
            if error != nil {
                return
            }
            /*
            "access_token" = "2.00Ah4f_EPcTAODab492e96570cFW9P";
            "expires_in" = 157679999;
            isRealName = true;
            "remind_in" = 157679999;
            uid = 3955144238;
             */
            
            guard  let dict = result else {
                return
            }
            
            let ua: UserAccout = UserAccout.init(dict: dict as! [String : AnyObject])
            
            // 请求用户信息
            self?.loadUserInfo(userAccout: ua)
        }
    }
}

// MARK: -请求用户信息
extension OAuthiewController {
    func loadUserInfo(userAccout: UserAccout) {
        
        guard let access_token = userAccout.access_token else {
            return
        }
        
        guard let uid = userAccout.uid else {
            return
        }
        
        HttpTool.shareInstance.loadUserInfo(access_token: access_token, uid: uid) { (result: AnyObject?, error: Error?) -> (Void) in
            
            if error != nil {
                mySelfLog(error)
                mySelfLog(error?.localizedDescription)
                return
            }
            
            guard let resultDict: [String : AnyObject] = result as! [String : AnyObject]? else {
                return
            }
            
            // 从字典内取出screen_name
            userAccout.screen_name = resultDict["screen_name"] as! String?
            userAccout.avatar_large = resultDict["avatar_large"] as! String?
            
            // 赋值
            UserAccoutViewModel.shareInstance.accout = userAccout
            
            // 保存对象
            NSKeyedArchiver.archiveRootObject(userAccout, toFile: UserAccoutViewModel.shareInstance.accoutPath)
            
            // 退出当前控制器
            self.dismiss(animated: true, completion: {
            
                // 显示欢迎界面
                UIApplication.shared.keyWindow?.rootViewController = WelcomeViewController()
                
            })

        }
    }
}

